package com.guat.servlet.user;

import com.google.gson.Gson;
import com.guat.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置前端返回数据使用UTF-8编码,防止乱码
        req.setCharacterEncoding("UTF-8");
        //获取前端传递的数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String type = req.getParameter("type");
        if (type == null){
            type = "普通用户";
        }

        UserService userService = new UserService();
        Map<String, Object> userRegisterMap = userService.addUser(username, password, type);

        //设置返回前端数据使用UTF-8编码,防止乱码
        resp.setCharacterEncoding("UTF-8");
        //将Map集合转换为json
        Gson gson = new Gson();
        String mapJson = gson.toJson(userRegisterMap);
        //将数据写入输入流中
        resp.getWriter().write(mapJson);
    }
}
